package com.zeildlin.seecode.util;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Component
public class SentitiveFilter {

    private static final Logger looger = LoggerFactory.getLogger(SentitiveFilter.class);

    //敏感词替换字符
    private static final String REPLACEMENT = "***";

    //根节点
    private TrieNode rootNode = new TrieNode();

    @PostConstruct
    public void init() {
        try (
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is))
        ) {
            String keyWord;
            while ((keyWord = reader.readLine() )!= null) {
                //添加到前缀树
                this.addKeyword(keyWord);
            }
        } catch (IOException e) {
            looger.error("敏感词加入失败" + e.getMessage());
        } finally {

        }

    }

    /*
    过滤敏感词
    参数 ： text 待过滤文本
    返回 ：过滤后的文本
     */
    public String filter(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        //指针1
        TrieNode tempNode = rootNode;
        //指针2
        int begin = 0;
        //指针3
        int position = 0;
        //过滤后字符
        StringBuilder sb = new StringBuilder();

        while (position < text.length()) {
            char c = text.charAt(position);
            //跳过符号
            if(isSymbol(c)||c == ','){
                //若指针1处于根节点，将此符号计入结果，让指针2向下走
                if(tempNode == rootNode){
                    sb.append(c);
                    begin++;
                }
                //无论符号在开头或者中间，指针3都向下走
                position++;
                continue;
            }
            //检查下级节点
            tempNode = tempNode.getSubNode(c);
            if (tempNode == null) {
                sb.append(c);
                position = ++begin;
                tempNode = rootNode;
            } else if (tempNode.isKeywordEnd() ) {
                sb.append(REPLACEMENT);
                begin = ++position;
                tempNode = rootNode;
            } else {
                position++;
                }
        }
        sb.append(text.substring(begin));

        return sb.toString();
    }

    //判断是否为符号
    private boolean isSymbol(Character c) {
        //c < 0x2E80 || c > 0x9FFF 文字范围
        return CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }

    //将一个敏感词添加到前缀树中去
    private void addKeyword(String keyword) {
        TrieNode tempNode = rootNode;
        int length = keyword.length();
        for (int i = 0; i < length; i++) {
            char c = keyword.charAt(i);
            TrieNode subNode = tempNode.getSubNode(c);
            if (subNode == null) {
                subNode = new TrieNode();
                tempNode.addSubNode(c, subNode);
            }
            //指向子节点，进入下一轮循环
            tempNode = subNode;
        }
        //敏感词结束标注
        tempNode.setKeywordEnd(true);
    }

    //前缀树
    private class TrieNode {
        // 关键词结束的标识
        private boolean isKeywordEnd = false;

        //子节点(key 下级字符，value 下级节点）
        private Map<Character, TrieNode> subNode = new HashMap<>();

        public boolean isKeywordEnd() {
            return isKeywordEnd;
        }

        public void setKeywordEnd(boolean keywordEnd) {
            isKeywordEnd = keywordEnd;
        }

        //添加子节点的方法
        public void addSubNode(Character c, TrieNode node) {
            subNode.put(c, node);
        }

        //获取子节点
        public TrieNode getSubNode(Character c) {
            return subNode.get(c);
        }
    }

}
